package beautiful.butterfly.distributed_service_container.socket.marshalling;

import beautiful.butterfly.distributed_service_container.socket.pojo.Request;
import beautiful.butterfly.distributed_service_container.socket.pojo.Response;
import beautiful.butterfly.distributed_service_container.socket.task.ITask;
import beautiful.butterfly.distributed_service_container.socket.task.TaskMap;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;


@Sharable
public class ServerHandler extends ChannelHandlerAdapter
{

    private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);

    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg)
            throws Exception
    {
        Request request = (Request) msg;
        //需要分析出task模块,mainModuleId,subModuleId
        //如果分析出错则返回错误编码,如果正确则返回业务信息<string>

        Response response = Response.newResponse(request);
        log.info("进行路由");
        if (!TaskMap.taskMap.containsKey(request.getMainModuleId()))
        {
            //没有找到module
            response.setContent("");
            response.setErrorCode(Response.error);
            response.setErrorMessage("没有找到MainModuleId");
        } else
        {
            Map<Long, ITask> taskMap = TaskMap.taskMap.get(request.getMainModuleId());
            if (!taskMap.containsKey(request.getSubModuleId()))
            {
                //没有找到module
                response.setContent("");
                response.setErrorCode(Response.error);
                response.setErrorMessage("没有找到SubModuleId");
            } else
            {
                ITask task = taskMap.get(request.getSubModuleId());
                try
                {
                    String content = task.doTask(request.getContent());
                    response.setContent(content);
                } catch (Exception e)
                {
                    response.setContent("");
                    response.setErrorCode(Response.error);
                    response.setErrorMessage(e.getMessage());
                }

            }
        }
        channelHandlerContext.writeAndFlush(response);

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    {
        cause.printStackTrace();
        ctx.close();// 发生异常，关闭链路
    }

}
